//
//  comDataHandle.m
//  穷游
//
//  Created by lanou3g on 15/12/22.
//  Copyright © 2015年 王忠奎. All rights reserved.
//

#import "comDataHandle.h"
#import "comModel.h"
static comDataHandle *_handle = nil;
@implementation comDataHandle

+(instancetype)sharedComDataHandle
{

    return [[self alloc]init];
    

}

+(instancetype)allocWithZone:(struct _NSZone *)zone
{

    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        if (_handle == nil) {
            _handle = [super allocWithZone:zone];
        }
    });
    return _handle;


}

#pragma mark ---请求数据
-(void)getComDataFromNet:(BLOCK)finishBlock
{

    NSString *string = @"http://open.qyer.com/qyer/bbs/forum_list?app_installtime=1435837675&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=31.13016009066801&lon=121.2839862196157&page=1&track_app_channel=App%2520Store&track_app_version=6.3&track_device_info=iPhone7%2C2&track_deviceid=94600906-5BB7-43E7-9E16-C479A03EE469&track_os=ios%25208.3&v=1";
    
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        @autoreleasepool {
            if (data == nil || error != nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    finishBlock(nil);
                    return;
                });
            }
            //解析数据
            NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",resultDict);
            
            NSArray *dataArray = resultDict[@"data"];
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
//            NSDictionary *dataDic = [dataArray objectAtIndex:0];
            for (NSDictionary *dataDic in dataArray) {
                NSArray *dataArr = dataDic[@"group"];
                
                for (NSDictionary *d in dataArr) {
                    comModel *model = [[comModel alloc]init];
                    model.name1= [d valueForKey:@"name"];
                    [model setValuesForKeysWithDictionary:d];
                    [array addObject:model];
                    NSLog(@"====%@",model.name1);
                }
            
            }
            self.comDataArray = [NSArray arrayWithArray:array];
            NSLog(@"*******%ld",self.comDataArray.count);
          
            //回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                finishBlock(self.comDataArray);
            });
            
            
        }
    }];
    [task resume];


}

@end
